package com.sixmac.service.impl;

import com.google.common.base.Strings;
import com.sixmac.common.model.system.Dict;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.StrKit;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.*;
import com.sixmac.pojo.Catalog;
import com.sixmac.service.IndexService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.*;

/**
 * Created by admin on 2018/7/4.
 */
@Service
public class IndexServiceImpl implements IndexService {


    public AjaxResult calu(Integer courseId, Integer userId) {
        AjaxResult res1 = new AjaxResult();
        AjaxResult res = new AjaxResult();
        ClientUserChapterRecord clientUserChapterRecord = Blade.create(ClientUserChapterRecord.class).findFirstBy("courseId = #{id} and userId = #{uid} order by createTime desc", CMap.init().put("id", courseId).put("uid", userId));
        if (clientUserChapterRecord != null) {
            Integer total = this.getTotal(courseId);
            Integer userTotal = this.getUserTotal(userId, courseId);
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(0);
            String result = numberFormat.format((float) userTotal / (float) total * 100);
            CourseChapter courseChapter = Blade.create(CourseChapter.class).findById(clientUserChapterRecord.getChapterId());
            res.setData(CMap.init().put("s", result).put("name", courseChapter.getName()).put("chapterId", clientUserChapterRecord.getChapterId()));
        } else {
            res.addError("找不到最近学习记录");
        }
        return res;
    }


    public String calus(Integer courseId, Integer userId) {
        Integer total = this.getTotal(courseId);
        Integer userTotal = this.getUserTotal(userId, courseId);
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(0);
        String result = numberFormat.format((float) userTotal / (float) total * 100);
        return result;
    }


    /**
     * 获取章节总数
     *
     * @param courseId
     * @return
     */
    private Integer getTotal(Integer courseId) {
        List<CourseChapter> courseChapterList = Blade.create(CourseChapter.class).findBy("courseId =#{courseId}", CMap.init().put("courseId", courseId));
        Integer total = 0;
        for (CourseChapter chapter : courseChapterList) {
            if (StrKit.isNotEmpty(chapter.getSafety())) {
                ++total;
            }
            if (StrKit.isNotEmpty(chapter.getUrl())) {
                ++total;
            }
            if (StrKit.isNotEmpty(chapter.getTechnology())) {
                ++total;
            }
            if (StrKit.isNotEmpty(chapter.getTest())) {
                ++total;
            }

        }
        return total;
    }

    private Integer getUserTotal(Integer userId, Integer courseId) {
        Integer total = 0;
        List<ClientUserChapterRecord> recordList = Blade.create(ClientUserChapterRecord.class).findBy("courseId =#{courseId} and userId = #{userId}", CMap.init().put("courseId", courseId).put("userId", userId));
        for (ClientUserChapterRecord record : recordList) {
            if (record.getSafety() != null) {
                ++total;
            }
            if (record.getVideo() != null) {
                ++total;
            }
            if (record.getTechnology() != null) {
                ++total;
            }
            if (record.getTest() != null) {
                ++total;
            }
        }
        return total;
    }


    public AjaxResult getPid(Integer examinId, Integer chapterId) {
        if (chapterId == 0) {
            return new AjaxResult().addSuccess("");
        }
        List<String> lists = new ArrayList<>();
        Integer n = 0;
        this.getNameByChapter(chapterId, lists, n);
        StringBuilder sb = new StringBuilder();
        Collections.reverse(lists);
        for (String s : lists) {
            sb.append(s);
            sb.append("-");
        }
        if (StrKit.isNotEmpty(sb.toString())) {
            CourseChapter courseChapter = Blade.create(CourseChapter.class).findById(chapterId);
            Map course = Db.selectOne("select id,name,content as point,image,url,pid,createtime,updatetime,level from t_course_chapter where pid = 0 and id =" + courseChapter.getCourseId());
            if (course == null) {
                return new AjaxResult().addError("课程不存在");
            }
            return new AjaxResult().setData(CMap.init().put("total", n).put("name", sb.substring(0, sb.length() - 1)).put("chapterId", chapterId).put("course", course));
        } else {
            return new AjaxResult().addError("名字为空");
        }
    }

    public void getNameByChapter(Integer id, List<String> lists, Integer num) {
        CourseChapter courseChapter = Blade.create(CourseChapter.class).findById(id);
        if (courseChapter != null) {
            lists.add(courseChapter.getName());
            this.getNameByChapter(courseChapter.getPid(), lists, num);

        }
    }


    private ClientUserChapterRecord getUserChapterRecord(Integer userId, Integer courseChapterId) {
        return Blade.create(ClientUserChapterRecord.class).findFirstBy("chapterId = #{id} and userId = #{uid}", CMap.init().put("id", courseChapterId).put("uid", userId));

    }


    @Override
    public void updateClientUserChapterRecord(Integer userId, Integer courseChapterId, Integer type, Integer examinId) {
        if (userId == 0) {
            return;
        }
        ClientUserChapterRecord clientUserChapterRecord = this.getUserChapterRecord(userId, courseChapterId);
        if (clientUserChapterRecord == null) {
            ClientUserChapterRecord record = new ClientUserChapterRecord();
            record.setChapterId(courseChapterId);
            record.setUserId(userId);
            record.setCourseId(examinId);
            this.switchChapterRecord(record, type);
            record.setCreateTime(new Date());
            Blade.create(ClientUserChapterRecord.class).save(record);
        } else {
            this.switchChapterRecord(clientUserChapterRecord, type);
            clientUserChapterRecord.setCourseId(examinId);
            Blade.create(ClientUserChapterRecord.class).update(clientUserChapterRecord);
        }

    }


    private void switchChapterRecord(ClientUserChapterRecord record, Integer type) {
        switch (type) {
            case 1:
                record.setSafety(1);
                break;
            case 2:
                record.setTechnology(1);
                break;
            case 3:
                record.setVideo(1);
                break;
            case 4:
                record.setVideo(2);
            case 5:
                record.setTest(1);
                break;
        }
    }

    private List<CourseChapter> getCatalogByPid(Integer pid, List<CourseChapter> courseChapters) {
        List<CourseChapter> list = new ArrayList<>();
        for (CourseChapter chapter : courseChapters) {
            if (chapter.getPid().compareTo(pid) == 0) {
                list.add(chapter);
            }
        }
        return list;

    }


    private String getDictByCode(Integer num, List<Dict> dicts) {
        if (num == null) {
            return null;
        }
        String s = null;
        for (Dict dict : dicts) {
            if (dict.getNum() == num) {
                s = dict.getName();
            }
        }
        return s;
    }


    private void convertCatalog(CourseChapter courseChapter, Integer userId, Catalog catalog, List<Dict> dicts) {
        ClientUserChapterRecord record = null;

        if (userId != null && userId != 0) {
            record = this.getUserChapterRecord(userId, courseChapter.getId());
        }

        catalog.setName(courseChapter.getName());
        catalog.setLevelName(this.getDictByCode(courseChapter.getLevel(), dicts));
        if (StrKit.isNotEmpty(courseChapter.getSafety())) {
            catalog.setSafety("1");
            if (record != null && record.getSafety() != null && record.getSafety() == 1) {
                catalog.setSafety("3");
            }
        } else {
            catalog.setSafety("2");
        }
        if (StrKit.isNotEmpty(courseChapter.getTechnology())) {
            catalog.setTechnology("1");
            if (record != null && record.getTechnology() != null && record.getTechnology() == 1) {
                catalog.setTechnology("3");
            }
        } else {
            catalog.setTechnology("2");
        }
        if (courseChapter.getUrl() != null && StringUtils.isNotBlank(courseChapter.getUrl())) {
            catalog.setVideo("1");
            if (record != null && record.getVideo() != null && record.getVideo() == 1) {
                catalog.setVideo("3");
            } else if (record != null && record.getVideo() != null && record.getVideo() == 2) {
                catalog.setVideo("4");
            }

        } else {
            catalog.setVideo("2");
        }
        if (StrKit.isNotEmpty(courseChapter.getTest())) {
            catalog.setTest(1);
            if (record != null && record.getTest() != null && record.getTest() == 1) {
                catalog.setTest(3);
            }
        } else {
            catalog.setTest(2);
        }
        catalog.setCourseChapterId(Convert.toStr(courseChapter.getId()));
     //   catalog.setSimulation(Convert.toStr(courseChapter.getSimulationId()));
        catalog.setSimulation(Convert.toStr(2));
    }


    private void getList(Integer userId, Integer id, List<CourseChapter> courseChapterList, List<Catalog> catalogList, List<Dict> dicts) {
        for (CourseChapter chapter : courseChapterList) {
            if (chapter.getPid().compareTo(id) == 0) {
                Catalog catalog = new Catalog();
                this.convertCatalog(chapter, userId, catalog, dicts);
                catalogList.add(catalog);
                this.getList(userId, chapter.getId(), courseChapterList, catalog.getList(), dicts);
            }
        }
    }

    private void addCourseChapter(Integer courseId) {
        CourseChapter c = Blade.create(CourseChapter.class).findById(courseId);
        Integer playNum = c.getPlaynum() == null ? 0 : c.getPlaynum();
        c.setPlaynum(++playNum);
        Blade.create(CourseChapter.class).update(c);
    }

    @Override
    public AjaxResult catalog(Integer courseId, Integer userId) {
        AjaxResult res = new AjaxResult();
        //播放量+1
        this.addCourseChapter(courseId);
        List<CourseChapter> courseChapters = Blade.create(CourseChapter.class).findBy("courseId = #{courseId} order by sort,createtime", CMap.init().put("courseId", courseId));
        List<CourseChapter> rootChapters = this.getCatalogByPid(courseId, courseChapters);
        List<Dict> dicts = Blade.create(Dict.class).findBy("code = 888 and num!=0", null);
        List<Catalog> courseChapterList = new ArrayList<>();
        for (CourseChapter courseChapter : rootChapters) {
            Catalog catalog = new Catalog();
            this.convertCatalog(courseChapter, userId, catalog, dicts);
            this.getList(userId, courseChapter.getId(), courseChapters, catalog.getList(), dicts);
            courseChapterList.add(catalog);
        }
        this.convertStatus(courseChapterList);
        return res.setData(courseChapterList);
    }


    private void convertStatus(List<Catalog> catalogList) {
        //一级
        for (Catalog catalog1 : catalogList) {
            catalog1.setStatus(2);
            System.out.println(catalog1.getName());
            if (catalog1.getList() == null || catalog1.getList().isEmpty())
                catalog1.setStatus(1);
            for (Catalog catalog2 : catalog1.getList()) {
                catalog2.setStatus(2);
                if (catalog2.getList() == null || catalog2.getList().isEmpty()) {
                    catalog2.setStatus(1);
                    catalog1.setStatus(1);
                }
                for (Catalog catalog3 : catalog2.getList()) {
                    catalog3.setStatus(2);

//                    if (!Strings.isNullOrEmpty(catalog3.getSafety()) && Convert.toInt(catalog3.getSafety()) != 3) {
//                        catalog3.setStatus(1);
//                        catalog2.setStatus(1);
//                        catalog1.setStatus(1);
//                    }
//                    if (!Strings.isNullOrEmpty(catalog3.getTechnology()) && Convert.toInt(catalog3.getTechnology()) != 3) {
//                        catalog3.setStatus(1);
//                        catalog2.setStatus(1);
//                        catalog1.setStatus(1);
//                    }
                    if (!Strings.isNullOrEmpty(Convert.toStr(catalog3.getTest())) && Convert.toInt(catalog3.getTest()) == 1) {
                        catalog3.setStatus(1);
                        catalog2.setStatus(1);
                        catalog1.setStatus(1);

                    }
                    if (!Strings.isNullOrEmpty(catalog3.getVideo()) && Convert.toInt(catalog3.getVideo()) == 1) {
                        catalog3.setStatus(1);
                        catalog2.setStatus(1);
                        catalog1.setStatus(1);

                    }


                }
            }

        }


    }


    @Override
    public AjaxResult getExaminList(ClienUser user, Integer courseChapterId, Integer courseId) {
        AjaxResult res = new AjaxResult();
        CourseChapter courseChapter = Blade.create(CourseChapter.class).findById(courseChapterId);
        if (courseChapter == null) {
            return res.addError("章节测试id找不到");
        }
        Examin examin = Blade.create(Examin.class).findById(courseChapter.getTest());
        if (examin == null) {
            return res.addError("考试找不到");
        }
        Map map = Db.selectOne("select count(*) as count,group_concat(id) as ids from t_examin_topic t where t.examineId = #{id}", CMap.init().put("id", courseChapter.getTest()));
        String ids[] = Convert.toStr(map.get("ids")).split(",");
        List<Map> list = Db.selectList(" select t.id,t.examineId,t.name,t.choice,t.image,t.reach,t.isTrue,a.content from t_examin_topic t inner join t_examin_topic_answer a on t.id=a.topicId  where 1=1 and t.id in (#{join(ids)})", CMap.init().put("ids", ids));
        return res.setData(CMap.init().put("list", list).put("total", list.size()));

    }
}
